package io.gitee.yxsnake.embark.web.core.utils;

import io.gitee.yxsnake.embark.web.core.constant.HeaderCons;
import io.gitee.yxsnake.embark.web.core.constant.StringPool;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.dromara.hutool.core.io.file.FileUtil;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author snake
 * @description
 * @since 2024/9/29 0:22
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileUtils extends FileUtil {

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) {
        String percentEncodedFileName = percentEncode(realFileName);
        String contentDispositionValue = "attachment; filename=%s;filename*=utf-8''%s".formatted(percentEncodedFileName, percentEncodedFileName);
        response.addHeader(HeaderCons.ACCESS_CONTROL_EXPOSE_HEADERS, "Content-Disposition,download-filename");
        response.setHeader(HeaderCons.CONTENT_DISPOSITION, contentDispositionValue);
        response.setHeader(HeaderCons.DOWNLOAD_FILENAME, percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
        return encode.replaceAll(StringPool.BACK_SLASH_PLUS, StringPool.PERCENT_URI_ENCODE);
    }
}

